// 新的事件管理器模块
(function (global) {
    class EventManager {
        constructor(game) {
            this.game = game;
            this.cardChoiceCallback = null;
            this.cardChoiceAllowCancel = true;
        }

        enterEvent() {
            const game = this.game;
            game.gameState = 'event';
            game.showScreen('event-screen');
            this.renderRandomEvent();
        }

        renderRandomEvent() {
            const game = this.game;
            const evt = this.generateRandomEvent();
            const titleEl = document.getElementById('event-title');
            const descEl = document.getElementById('event-desc');
            const optionsEl = document.getElementById('event-options');
            const continueBtn = document.getElementById('event-continue');

            if (!titleEl || !descEl || !optionsEl || !continueBtn) {
                console.error('事件界面元素未找到');
                return;
            }

            this.updateEventUI();

            titleEl.textContent = evt.title || '奇遇事件';
            descEl.innerHTML = evt.description || '';
            optionsEl.innerHTML = '';
            optionsEl.style.display = 'flex';
            optionsEl.style.opacity = '1';
            continueBtn.style.display = 'none';

            if (!evt.options || evt.options.length === 0) {
                console.error('事件没有选项:', evt);
                optionsEl.innerHTML = '<p style="color: #ff6666;">事件选项加载失败</p>';
                return;
            }

            evt.options.forEach(opt => {
                const btn = document.createElement('button');
                btn.className = 'btn-primary';
                btn.textContent = opt.text || '选项';
                btn.addEventListener('click', async () => {
                    Array.from(optionsEl.querySelectorAll('button')).forEach(b => b.disabled = true);
                    try {
                        if (opt.action) {
                            await opt.action();
                        }
                    } catch (e) {
                        console.error('事件选项执行错误:', e);
                    }
                    this.updateEventUI();
                    optionsEl.style.transition = 'opacity 0.3s ease-out';
                    optionsEl.style.opacity = '0';
                    setTimeout(() => { optionsEl.style.display = 'none'; }, 300);
                    continueBtn.style.display = 'inline-block';
                });
                optionsEl.appendChild(btn);
            });

            continueBtn.onclick = () => {
                game.continueAdventure();
            };
        }

        updateEventUI() {
            const game = this.game;
            if (!game.player) return;

            const avatar = document.getElementById('event-player-avatar');
            if (avatar && game.selectedCharacter) {
                const frames = game.getCharacterAvatarFrames(game.selectedCharacter);
                game.startAvatarAnimation('event-player-avatar', frames);
            }

            const health = document.getElementById('event-player-health');
            const maxHealth = document.getElementById('event-player-max-health');
            if (health) health.textContent = game.player.health;
            if (maxHealth) maxHealth.textContent = game.player.maxHealth;

            const energy = document.getElementById('event-player-energy');
            if (energy) energy.textContent = game.player.energy;

            const gold = document.getElementById('event-player-gold');
            if (gold) gold.textContent = game.playerGold;

            const strength = document.getElementById('event-player-strength');
            const dexterity = document.getElementById('event-player-dexterity');
            const intelligence = document.getElementById('event-player-intelligence');
            if (strength) strength.textContent = game.player.strength;
            if (dexterity) dexterity.textContent = game.player.dexterity;
            if (intelligence) intelligence.textContent = game.player.intelligence;

            const deckCount = document.getElementById('event-deck-count');
            if (deckCount) {
                const totalCount = game.playerDeck.length + game.playerDiscardPile.length;
                deckCount.textContent = totalCount;
            }

            const relicsCount = document.getElementById('event-relics-count');
            if (relicsCount) {
                relicsCount.textContent = game.playerRelics ? game.playerRelics.length : 0;
            }
        }

        generateRandomEvent() {
            const events = [
                () => this.eventLuckyWheel(),
                () => this.eventLibraryStudy(),
                () => this.eventHometownTrip(),
                () => this.eventParkTrip(),
                () => this.eventMallWeekend()
            ];
            const pick = events[Math.floor(Math.random() * events.length)];
            return pick();
        }

        eventLuckyWheel() {
            const game = this.game;
            return {
                title: '路边的幸运转盘',
                description: '有一天走在路上，看到一位小贩在摆摊，招呼你来玩"幸运转盘"。你要做什么？',
                options: [
                    { text: '1）谢谢，不需要', action: async () => { game.addBattleLog('你婉拒了小贩的邀请。'); } },
                    { text: '2）给小贩 75 金币（或许会有惊喜？）', action: async () => {
                        if (game.playerGold < 75) { game.addBattleLog('金币不足，无法参与。'); return; }
                        game.playerGold -= 75; game.updateUI();
                        game.addBattleLog('你付给了小贩 75 金币。');
                    }},
                    { text: '3）获得 120 金币', action: async () => { game.playerGold += 120; game.updateUI(); game.addBattleLog('你幸运地获得了 120 金币！'); }},
                    { text: '4）获得随机遗物', action: async () => {
                        const all = relicDatabase.getAllRelics();
                        const relic = all[Math.floor(Math.random() * all.length)];
                        game.playerRelics.push(relic);
                        game.addBattleLog(`获得遗物：${relic.name}`);
                        game.updateRelicsDisplay();
                        game.updateMapRelicsDisplay();
                    }},
                    { text: '5）获得随机通用稀有卡牌', action: async () => {
                        const pool = cardDatabase.getCommonCardsByRarity('rare');
                        if (pool.length === 0) { game.addBattleLog('似乎什么也没有发生。'); return; }
                        const base = pool[Math.floor(Math.random() * pool.length)];
                        const newCard = this.cloneCardTemplate(base);
                        if (newCard) {
                            game.playerDeck.push(newCard);
                            game.addBattleLog(`获得通用稀有卡牌：${newCard.name}`);
                            game.updateDeckCounts();
                        }
                    }}
                ]
            };
        }

        eventLibraryStudy() {
            const game = this.game;
            return {
                title: '图书馆自修',
                description: '来到图书馆，你会选择哪类书籍？',
                options: [
                    { text: '1）看理科书：随机升级手中 2 张攻击牌', action: async () => {
                        const upgraded = game.upgradeRandomHandCardsByType('attack', 2);
                        if (upgraded === 0) game.addBattleLog('你没有可升级的攻击牌。');
                        game.updateHandDisplay();
                    }},
                    { text: '2）看文科书：随机升级 2 张技能牌', action: async () => {
                        const upgraded = game.upgradeRandomFromAllByType('skill', 2);
                        if (upgraded === 0) game.addBattleLog('没有可升级的技能牌。');
                        game.updateUI();
                    }},
                    { text: '3）看杂书：随机升级手中 2 张防御牌', action: async () => {
                        const upgraded = game.upgradeRandomHandCardsByType('defend', 2);
                        if (upgraded === 0) game.addBattleLog('你手里没有可升级的防御牌。');
                        game.updateHandDisplay();
                    }}
                ]
            };
        }

        eventHometownTrip() {
            const game = this.game;
            return {
                title: '回老家帮忙',
                description: '回到老家，正好有些事情可以出力。你要做什么？',
                options: [
                    { text: '1）帮忙浇水：最大生命 +15', action: async () => {
                        game.player.max_life_bonus = (game.player.max_life_bonus || 0) + 15;
                        game.player.maxHealth += 15; game.player.health += 15; game.updateUI();
                        game.addBattleLog('你认真浇水，体魄更强健了：最大生命 +15');
                    }},
                    { text: '2）整理杂物间：获得随机事件遗物', action: async () => {
                        const relic = relicDatabase.getRandomRelic('rare');
                        if (relic) {
                            game.playerRelics.push(relic);
                            game.addBattleLog(`你找到了一件珍贵的遗物：${relic.name}`);
                            game.updateRelicsDisplay();
                            game.updateMapRelicsDisplay();
                        }
                    }},
                    { text: '3）去树林玩：随机升级 1 张牌，并移除 1 张牌', action: async () => {
                        const upCnt = game.upgradeRandomFromAllByType(null, 1);
                        if (upCnt > 0) game.addBattleLog('你领悟良多，随机升级了1张牌'); else game.addBattleLog('没有可升级的牌');
                        const removed = game.removeRandomFromDeck(1);
                        if (removed > 0) game.addBattleLog('你丢弃了 1 张不需要的牌'); else game.addBattleLog('没有可移除的牌');
                        game.updateUI();
                    }}
                ]
            };
        }

        eventParkTrip() {
            const game = this.game;
            return {
                title: '公园的意外',
                description: `${this.eventParkTripMessage()} 你打算怎么做？`,
                options: [
                    { text: '1）拿走：获得 150 金币（道德受损）', action: async () => {
                        game.playerGold += 150; game.updateUI();
                        game.addBattleLog('你收好金币，心中略有愧疚……');
                    }},
                    { text: '2）上交：获得「拾金不昧奖章」', action: async () => {
                        const medal = new Relic('拾金不昧奖章', '战斗开始时获得3点临时力量与敏捷（持续1回合）', { type: 'trigger' }, 'rare');
                        game.player.moral_honesty = true;
                        game.player.action_medal_obtained = true;
                        game.playerRelics.push(medal);
                        game.addBattleLog('你获得了「拾金不昧奖章」！');
                        game.updateRelicsDisplay();
                        game.updateMapRelicsDisplay();
                    }},
                    { text: '3）原地放回：获得稀有卡「心无旁骛」', action: async () => {
                        const focus = new Card('心无旁骛', 1, 'skill', 0, '打出后：你的下一张牌会额外触发一次。升级：下一张牌额外触发两次。', [], false, 'rare', 'power');
                        game.playerDeck.push(focus);
                        game.addBattleLog('你放下私心，获得了卡牌「心无旁骛」。');
                        game.updateDeckCounts();
                    }}
                ]
            };
        }

        eventParkTripMessage() {
            return '路上你捡到了一个鼓鼓的红包，里面有 150 枚金币。';
        }

        eventMallWeekend() {
            const game = this.game;
            return {
                title: '周末逛商场',
                description: '周末逛商场，你打算做什么？',
                options: [
                    { text: '1）星巴克静心：移除 2 张卡牌', action: async () => {
                        const removed = game.removeRandomFromDeck(2);
                        if (game.addBanner) game.addBanner(`已移除 ${removed} 张卡牌`);
                        game.addBattleLog(`你在咖啡香中清理了卡组（移除${removed}张）`);
                        game.updateDeckCounts();
                    }},
                    { text: '2）喝奶茶：血量回满', action: async () => {
                        game.player.health = game.player.maxHealth; game.updateUI();
                        game.addBattleLog('美味的奶茶让你精力充沛，生命回满！');
                    }},
                    { text: '3）买文具：获得随机事件遗物', action: async () => {
                        const relic = relicDatabase.getRandomRelic('rare');
                        if (relic) {
                            game.playerRelics.push(relic);
                            game.addBattleLog(`你买到了稀有的「${relic.name}」！`);
                            game.updateRelicsDisplay();
                            game.updateMapRelicsDisplay();
                        }
                    }}
                ]
            };
        }

        triggerHeavenlyBlessing() {
            const game = this.game;
            if (game.heavenlyBlessingResolved || !game.player) return;
            game.gameState = 'event';
            game.showScreen('event-screen');
            this.renderHeavenlyBlessingEvent();
        }

        renderHeavenlyBlessingEvent() {
            const titleEl = document.getElementById('event-title');
            const descEl = document.getElementById('event-desc');
            const optionsEl = document.getElementById('event-options');
            const continueBtn = document.getElementById('event-continue');
            if (!titleEl || !descEl || !optionsEl) return;

            titleEl.textContent = '文曲星赐福';
            descEl.textContent = '文曲星驾云而至，赐予你开局的选择：';
            optionsEl.innerHTML = '';
            if (continueBtn) {
                continueBtn.style.display = 'none';
                continueBtn.textContent = '返回地图';
                continueBtn.onclick = () => this.finishHeavenlyBlessing();
            }

            const options = [
                { key: 'rareCard', text: 'A. 折损血气：随机获得1张稀有卡牌，失去25%当前生命' },
                { key: 'cardChoice', text: 'B. 精挑细选：从普通/罕见卡牌中三选一' },
                { key: 'commonRelic', text: 'C. 平稳起步：获得1件随机普通遗物' },
                { key: 'maxHealth', text: 'D. 强身健体：最大生命值提升25%' },
                { key: 'upgradeAndPotion', text: 'E. 着手准备：随机升级2张牌并获得1瓶随机药水' }
            ];

            options.forEach(opt => {
                const btn = document.createElement('button');
                btn.className = 'btn-secondary';
                btn.textContent = opt.text;
                btn.addEventListener('click', () => {
                    this.handleHeavenlyBlessingOption(opt.key);
                });
                optionsEl.appendChild(btn);
            });
        }

        handleHeavenlyBlessingOption(option) {
            const game = this.game;
            const optionsEl = document.getElementById('event-options');
            if (optionsEl) {
                optionsEl.querySelectorAll('button').forEach(btn => btn.disabled = true);
            }

            switch (option) {
                case 'rareCard': {
                    const rarePool = [
                        ...(cardDatabase.getCharacterCardsByRarity(game.selectedCharacter, 'rare') || []),
                        ...(cardDatabase.getCommonCardsByRarity('rare') || [])
                    ];
                    let pool = rarePool;
                    if (!pool.length) {
                        pool = [
                            ...(cardDatabase.getCharacterCardsByRarity(game.selectedCharacter, 'uncommon') || []),
                            ...(cardDatabase.getCommonCardsByRarity('uncommon') || [])
                        ];
                    }
                    if (pool.length) {
                        const base = pool[Math.floor(Math.random() * pool.length)];
                        const newCard = this.cloneCardTemplate(base);
                        if (newCard) {
                            game.playerDeck.push(newCard);
                            game.addBattleLog(`文曲星赐福：获得稀有卡牌 ${newCard.name}`);
                            game.updateDeckCounts();
                            const lose = Math.max(1, Math.floor(game.player.health * 0.25));
                            game.player.health = Math.max(1, game.player.health - lose);
                            game.updateUI();
                            this.showHeavenlyBlessingResult(`你冒着风险凝视星辉，换来卡牌 <strong>${newCard.name}</strong>，同时失去 <strong>${lose}</strong> 点生命。`);
                            return;
                        }
                    }
                    this.showHeavenlyBlessingResult('星辉闪烁，但似乎没有带来新的启示，赐福落空。');
                    break;
                }
                case 'cardChoice': {
                    const choicePool = [
                        ...(cardDatabase.getCharacterCardsByRarity(game.selectedCharacter, 'common') || []),
                        ...(cardDatabase.getCharacterCardsByRarity(game.selectedCharacter, 'uncommon') || []),
                        ...(cardDatabase.getCommonCardsByRarity('common') || []),
                        ...(cardDatabase.getCommonCardsByRarity('uncommon') || [])
                    ];
                    if (!choicePool.length) {
                        this.showHeavenlyBlessingResult('星辉中没有显现出新的卡牌。');
                        return;
                    }
                    const shuffled = [...choicePool].sort(() => 0.5 - Math.random());
                    const candidates = shuffled.slice(0, Math.min(3, shuffled.length)).map(base => this.cloneCardTemplate(base)).filter(Boolean);
                    if (!candidates.length) {
                        this.showHeavenlyBlessingResult('卡牌虚影一闪而逝，赐福没有成功。');
                        return;
                    }
                    this.showHeavenlyBlessingResult('请选择一张卡牌带走。', false);
                    this.openCardChoiceModal(candidates, {
                        title: '文曲星赐福：选择一张卡牌',
                        allowCancel: false,
                        onSelect: (card) => {
                            if (card) {
                                const newCard = this.cloneCardTemplate(card);
                                if (newCard) {
                                    game.playerDeck.push(newCard);
                                    game.addBattleLog(`文曲星赐福：选择了卡牌 ${newCard.name}`);
                                    game.updateDeckCounts();
                                    this.showHeavenlyBlessingResult(`你谨慎挑选，最终收下了 <strong>${newCard.name}</strong>。`);
                                    return;
                                }
                            }
                            this.showHeavenlyBlessingResult('你犹豫片刻，星辉消散，赐福无功而返。');
                        }
                    });
                    break;
                }
                case 'commonRelic': {
                    const relic = relicDatabase.getRandomRelic('common');
                    if (relic) {
                        const granted = new Relic(relic.name, relic.description, relic.effect, relic.rarity);
                        game.playerRelics.push(granted);
                        game.addBattleLog(`文曲星赐福：获得遗物 ${granted.name}`);
                        game.updateRelicsDisplay();
                        game.updateMapRelicsDisplay();
                        this.showHeavenlyBlessingResult(`文曲星赠与你遗物 <strong>${granted.name}</strong>。`);
                    } else {
                        this.showHeavenlyBlessingResult('星辉中没有新的遗物出现。');
                    }
                    break;
                }
                case 'maxHealth': {
                    const gain = Math.max(1, Math.floor(game.player.maxHealth * 0.25));
                    game.player.maxHealth += gain;
                    game.player.health += gain;
                    game.addBattleLog(`文曲星赐福：最大生命 +${gain}，当前生命同步提升`);
                    game.updateUI();
                    this.showHeavenlyBlessingResult(`星辉护体，最大生命提升 <strong>${gain}</strong> 点，并恢复同等生命。`);
                    break;
                }
                case 'upgradeAndPotion': {
                    const upgraded = game.upgradeRandomFromAllByType(null, 2);
                    if (upgraded > 0) {
                        game.addBattleLog(`文曲星赐福：随机升级 ${upgraded} 张卡牌`);
                    }
                    const potion = this.clonePotion(this.getRandomStartingPotion());
                    let potionText = '';
                    if (potion) {
                        game.playerPotions.push(potion);
                        game.addBattleLog(`文曲星赐福：获得药水 ${potion.name}`);
                        game.updatePotionsDisplay();
                        if (game.updateMapPotionsDisplay) {
                            game.updateMapPotionsDisplay();
                        }
                        potionText = `并获得药水 <strong>${potion.name}</strong>`;
                    }
                    if (upgraded === 0 && !potionText) {
                        this.showHeavenlyBlessingResult('星辉闪烁，但似乎没有留下实质的馈赠。');
                    } else {
                        const upgradeText = upgraded > 0 ? `随机升级 <strong>${upgraded}</strong> 张卡牌` : '';
                        const connector = upgradeText && potionText ? '，' : '';
                        this.showHeavenlyBlessingResult(`文曲星庇护：${upgradeText}${connector}${potionText}。`);
                    }
                    break;
                }
                default:
                    this.showHeavenlyBlessingResult('星辉归于宁静，没有新的变化。');
                    break;
            }
        }

        finishHeavenlyBlessing() {
            const game = this.game;
            game.heavenlyBlessingResolved = true;
            this.closeCardChoiceModal();
            game.gameState = 'playing';
            game.showMap();
            game.updateMapUI();
            game.updateUI();
        }

        showHeavenlyBlessingResult(message, allowContinue = true) {
            const descEl = document.getElementById('event-desc');
            const optionsEl = document.getElementById('event-options');
            const continueBtn = document.getElementById('event-continue');
            if (descEl) {
                descEl.innerHTML = `<div class="event-result">${message}</div>`;
            }
            if (optionsEl) {
                optionsEl.innerHTML = '';
                optionsEl.style.display = 'none';
            }
            if (continueBtn) {
                continueBtn.style.display = allowContinue ? 'inline-block' : 'none';
            }
        }

        openCardChoiceModal(cards, options = {}) {
            const modal = document.getElementById('card-choice-modal');
            const list = document.getElementById('card-choice-list');
            const titleEl = document.getElementById('card-choice-title');
            const cancelBtn = document.getElementById('card-choice-cancel');
            if (!modal || !list) return;

            list.innerHTML = '';
            const title = options.title || '选择一张卡牌';
            if (titleEl) titleEl.textContent = title;
            this.cardChoiceCallback = options.onSelect || null;
            this.cardChoiceAllowCancel = options.allowCancel !== false;
            if (cancelBtn) {
                cancelBtn.style.display = this.cardChoiceAllowCancel ? 'inline-flex' : 'none';
            }

            (cards || []).forEach(card => {
                const cardElement = document.createElement('div');
                cardElement.className = `deck-card rarity-${card.rarity || 'common'} card-role-${this.game.getCardRole(card)}`;
                cardElement.innerHTML = this.game.renderCardContent(card, { mode: 'preview' });
                cardElement.addEventListener('click', () => {
                    if (this.cardChoiceCallback) {
                        this.cardChoiceCallback(card);
                    }
                    this.closeCardChoiceModal();
                });
                list.appendChild(cardElement);
            });

            modal.classList.add('active');
        }

        closeCardChoiceModal(cancelled = false) {
            const modal = document.getElementById('card-choice-modal');
            const list = document.getElementById('card-choice-list');
            if (modal) {
                modal.classList.remove('active');
            }
            if (list) {
                list.innerHTML = '';
            }
            if (cancelled && this.cardChoiceAllowCancel && this.cardChoiceCallback) {
                this.cardChoiceCallback(null);
            }
            this.cardChoiceCallback = null;
        }

        cloneCardTemplate(baseCard) {
            if (!baseCard) return null;
            const cloned = new Card(
                baseCard.name,
                baseCard.cost,
                baseCard.type,
                baseCard.value,
                baseCard.description,
                baseCard.effects || [],
                baseCard.isSpell || false,
                baseCard.rarity || 'common',
                baseCard.role || null
            );
            if (baseCard.upgraded) {
                cloned.upgraded = true;
            }
            return cloned;
        }

        clonePotion(potion) {
            if (!potion) return null;
            return {
                name: potion.name,
                description: potion.description,
                effect: potion.effect ? { ...potion.effect } : undefined,
                rarity: potion.rarity || 'common'
            };
        }

        getRandomStartingPotion() {
            const potion = this.game.getRandomPotion();
            return potion ? { ...potion } : null;
        }
    }

    global.EventManager = EventManager;
})(window);
